import { getDesigncourselist } from '@/request/designcourse'
import { getChooselist, getCurriculumlist, getCourselist } from '@/request/courses'
import { endCurrCourse } from "@/request/teacher";
import { TeacherOfTheCourse } from "@/util/teacherAuth.js";
import { Message } from 'ant-design-vue';
import user from "./user.js"

const state = {
  CurrState: {
    IsTeachingButOpen: '已开课但可选',
    IsStudyButOpen: '已开课但可选',
    IsTeachingAndClosed: '已开课不可选',
    // IsEnded: '已结课不可选',
    IsClosed: '不可选',
    IsKeepOpen: '保持可选',
    IsEnded: '已结课',
    IsOpen: '可选',
    IsRemoved: '撤销'
  },
  courses: [],
  deleteCourses: [],
  chooseCourses: [], // 已选课列表
  designcourselist: [], // 设计课程列表
  publishedCourses: [], // 已发布的课程
  myDesigningCourses: [], // 我正在设计的课程
  otherDesigncourselist: [], // 他人的课程
  currCourses: [], // 所有已开设的课程
  myTeaching: [], // 我正在教授的课程
  endTeaching: [], // 已结课的课程
  end: [], // 所有已结课课程
  removeTrackCourses: [],
  filterChooseCourses: [],
  designDeleteCourses: [], // 创作课程已删除课程
}

const mutations = {
  // 可开设的课程
  changeCourse(state, payload) {
    state.courses = payload
  },
  // 已撤销课程
  changeDeleteCourse(state, payload) {
    state.deleteCourses = payload
  },
  // 已选课程
  changeChooseCourses(state, payload) {
    state.chooseCourses = payload
  },
  // 创作系统课程列表
  changeDesignCourses(state, payload) {
    state.designcourselist = payload
  },
  // 已发布的课程
  changePublishedCourses(state, payload) {
    state.publishedCourses = payload
  },
  // // 创作系统课程列表
  changemyDesignCourses(state, payload) {
    state.myDesigningCourses = payload
  },
  changeOhterDesignCourses(state, payload) {
    state.otherDesigncourselist = payload
  },
  // 创作课程已删除的课程
  changeDesignDeleteCourses(state, payload) {
    state.designDeleteCourses = payload
  },
  // 修改所有已开设的课程数据
  changeCurrCourses(state, payload) {
    state.currCourses = payload
  },
  // 正在教授的课程
  changeMyTeachingCourses(state, payload) {
    state.myTeaching = payload
  },
  // 已结课的课程
  changeEndTeachingCourses(state, payload) {
    state.endTeaching = payload
  },
  // 所有已结课的课程
  changeEndCourses(state, payload) {
    state.end = payload
  },
  // 已过滤的已选课程
  changeFilterChooseCourses(state, payload) {
    state.filterChooseCourses = payload
  },
  setTremoveTrackCourses(state, payload) {
    var name = payload + "=";
    var ca = document.cookie.split(';');
    state.removeTrackCourses = []
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i].trim();
      if (c.indexOf(name) == 0) {
        state.removeTrackCourses = JSON.parse(c.substring(name.length, c.length))
        return
      }
    }
  },
}

const actions = {
  fetchCourses({state, commit, dispatch}, ) {
    getCourselist().then(data => {
      commit("changeCourse", data)
    })
  },
  fetchChooseCourses({
    state,
    commit,
    dispatch
  }, params) {
    getChooselist({
      userID: user.state.userInfo.userID,
    }).then(data => {
      if (data) {
        data.forEach(item => {
          params.$set(item, 'type', '学习')
          params.$set(item, 'name', item.name.split('_')[0])
        })
        commit('changeChooseCourses', data)
        dispatch("updateChoosesCourseAndDesignCourse")
      }
    })
  },
  // 获取设计中的课程
  fetchDesignCourses({
    state, commit, dispatch
  }, params) {
    getDesigncourselist().then(data => {
      // if (res.errno === 0) {
        params?.that && data.forEach(item => params?.that.$set(item, 'type', '创作'))
        commit('changeDesignCourses', JSON.parse(JSON.stringify(data)))
        let isPublished = data?.filter((item) =>(item.state == "已发布") && [43, 44, 48].indexOf(item.courseID) == -1)?.filter(item => (item.mainDesignerUserID === user.state.userInfo.userID) || (item.otherDesigerUserIDList && item.otherDesigerUserIDList?.indexOf(user.state.userInfo.userID) !== -1));
        let otherCourses = data?.filter(item => (item.mainDesignerUserID !== user.state.userInfo.userID) && (!item.otherDesigerUserIDList || (item.otherDesigerUserIDList && item.otherDesigerUserIDList?.indexOf(user.state.userInfo.userID) == -1)))
        data = data?.filter(item => (item.mainDesignerUserID === user.state.userInfo.userID) || (item.otherDesigerUserIDList && item.otherDesigerUserIDList?.indexOf(user.state.userInfo.userID) !== -1))
        let isDesigning = data.filter((item) =>(item.state == "创作中" || item.state == "已提交" || item.state == "已发布"))
        commit('changemyDesignCourses', isDesigning)
        commit('changePublishedCourses', isPublished)
        commit('changeOhterDesignCourses', otherCourses)
        if (params?.that) dispatch("updateChoosesCourseAndDesignCourse")
      // }
    })
  },
  // 获取我的课程
  getMyCourses({ state, commit, dispatch }, params) {
    if (user.state.userInfo.accessToken) {
      if (user.state.userInfo.authNum.indexOf(1) !== -1) {
        dispatch("fetchChooseCourses", params.that);
      }
      if (user.state.userInfo.authNum.indexOf(64) !== -1) {
        dispatch("fetchDesignCourses", params);
      }
    }
  },
  // 过滤掉需要隐藏的课程
  removeTrackCourses({
    state,
    commit,
    dispatch,
    store
  }, params) {
    let removeArr = []
    commit('setTremoveTrackCourses', 'rTCs')
    removeArr = state.removeTrackCourses
    if (removeArr.filter(item => (item.currNo === params.currNo && item.courseID === params.courseID) && item.type === params.type && item.userID === user.state.userInfo.userID).length === 0) {
      removeArr.push({
        courseID: params.courseID,
        currNo: params.currNo,
        type: params.type,
        userID: user.state.userInfo.userID
      })
    }
    commit('user/setCookies', { name: 'rTCs', val: removeArr }, { root: true })
    dispatch('updateChoosesCourseAndDesignCourse')
  },
  // 更新我的课程列表
  updateChoosesCourseAndDesignCourse({ state, commit, dispatch }, params) {
    commit('setTremoveTrackCourses', 'rTCs')
    let removeArr = state.removeTrackCourses
    let newChoose = []
    let newDesign = []
    let designcourselist = JSON.parse(JSON.stringify(state.designcourselist))
    let chooseCourses = JSON.parse(JSON.stringify(state.chooseCourses))
    let filterRA_D = removeArr.filter((ritem, rindex) => ritem.type === '创作' && ritem.userID === user.state.userInfo.userID)
    let filterRA_C = removeArr.filter((ritem, rindex) => ritem.type === '学习' && ritem.userID === user.state.userInfo.userID)
    newDesign = [...designcourselist].filter(x => [...filterRA_D].every(y => y.courseID !== x.courseID && user.state.userInfo.userID == y.userID));
    newChoose = [...chooseCourses].filter(x => [...filterRA_C].every(y => {
      return y.currNo !== x.currNo
    }));
    commit('changeFilterChooseCourses', newChoose)
    commit('changeDesignCourses', newDesign)
  },
  // 获取已开设的所有课程
  fetchCoursesList({ state, commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      getCurriculumlist(params).then((data) => {
        // 获取撤销课程
        if (params?.state == "撤销") {
          let newData = data?.filter(
            (item) => item.publishStaffUserID == user.state.userInfo.userID
          );
          return commit("changeDeleteCourse", newData)
        }
        // 获取已开设课程
        if (params?.state == '已结课') {
          commit('changeEndCourses', data)
        }
        if (data && data.length) {
          commit("changeCurrCourses", data.reverse())
          let hAuth = [2, 32, 64].find(item => user.state.userInfo?.authNum?.some(sitem => sitem == item))
          data = data?.filter((item) => {
            // 学生
            if (!hAuth) {
              // 过滤特殊课程
              if (item.currNo == 6 && item.courseID === 8) {
                if ([225].indexOf(user.state.userInfo.userID) !== -1) {
                  return item;
                }
              } else {
                return item;
              }
            }
            // 教师
            if (hAuth) {
              return TeacherOfTheCourse(item, user.state.userInfo)
            }
          });
          if (hAuth) {
            dispatch("filterCurrCoursesState", { data: data, state: [state.CurrState.IsOpen, state.CurrState.IsKeepOpen, state.CurrState.IsClosed] }) // IsOpen
            dispatch("filterCurrCoursesState", { data: data, state: [state.CurrState.IsEnded] })
          }
          resolve(data || [])
        } else {
          resolve(false)
        }
      }).catch(err => {
        reject(err)
      });
    })
  },
  filterCurrCoursesState({ state, commit, dispatch }, params) {
    const stateKey = {}
    stateKey[state.CurrState.IsKeepOpen] = { "myTeaching": "changeMyTeachingCourses" } // IsOpen
    stateKey[state.CurrState.IsOpen] = { "myTeaching": "changeMyTeachingCourses" } // IsOpen
    stateKey[state.CurrState.IsEnded] = { "endTeaching": "changeEndTeachingCourses" }
    let data = params.data
    data = data.filter(item => params.state.some(sitem => sitem == item.state))
    params.state.forEach(item => {
      const value = stateKey[item]
      if (value) {
        commit(`${Object.values(value)?.[0]}`, data);
      }
    })
  },
  endCourse({ state, commit, dispatch }, params) {
    return new Promise((resolve, rjeect) => {
      let data = params.params
      const isCancel = params.isCancel
      endCurrCourse(data)
        .then((res) => {
          if (res.errno === 0) {
            Message.success({
              content: isCancel ? "取消结课" : "结课成功!",
            });
            resolve(true)
          } else {
            Message.error({
              content: res.message || "结课失败!",
            });
            resolve(false)
          }
        })
        .catch((err) => {
          resolve("catch")
        });
    })
  },
  // 重新过滤已开课程不同状态的课程
  filterCoursesState({ state, commit, dispatch }, params) {
    let changeToEnd = params.changeToEnd ? state.CurrState.IsEnded : state.CurrState.IsKeepOpen // IsOpen
    let data = params.changeToEnd ? state.currCourses : state.endTeaching
    data = JSON.parse(JSON.stringify(data))
    data.forEach((item) => {
      if (item.currNo === params.currNo) {
        item.state = changeToEnd;
      }
    });
    if (changeToEnd) {
      dispatch("changeCurrCourses", data);
    } else {
      dispatch("changeEndTeachingCourses", data);
    }
    dispatch("filterCurrCoursesState", { data: data, state: [state.CurrState.IsKeepOpen] }); // IsOpen
    dispatch("filterCurrCoursesState", { data: data, state: [state.CurrState.IsOpen] }); // IsOpen
    dispatch("filterCurrCoursesState", { data: data, state: [state.CurrState.IsEnded] });
  },
  removeMyAllCourse({ state, commit, dispatch}) {
    commit("changeChooseCourses", [])
    commit("changeDesignCourses", [])
    commit("changeMyTeachingCourses", [])
    commit("changeEndTeachingCourses", [])
    commit("changeFilterChooseCourses", [])
  },
  // 获取所有课程
  fetchDesignDeteleCoursesList({state, commit, dispatch}) {
    getDesigncourselist({
      state: "已删除",
    }).then((data) => {
      if (data) {
        data = data?.filter((item) => item.state == "已删除");
        data.sort((a, b) => {
          let t_1 = new Date(a.lastUpdatedTime).getTime();
          let t_2 = new Date(b.lastUpdatedTime).getTime();
          return t_2 - t_1;
        });
        // this.coursesData = data;
        commit('changeDesignDeleteCourses', data)
      } else {
        this.$antdMessage.error({
          content: "获取已删除的课程失败",
        });
      }
    });
  },
}


export default {
  namespaced: true,
  state,
  mutations,
  actions,
}